<template>
  <div class="guide-list-container">
    <el-card>
      <div slot="header" class="card-header">
        <span>解说员列表</span>
        <el-input
          placeholder="搜索解说员姓名"
          v-model="searchQuery"
          class="search-input"
          clearable
          @clear="getGuideList"
          @keyup.enter.native="searchGuides"
        >
          <el-button slot="append" icon="el-icon-search" @click="searchGuides"></el-button>
        </el-input>
      </div>
      
      <!-- 解说员列表 -->
      <el-row :gutter="20" v-loading="loading">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="item in guideList" :key="item.id" class="guide-item">
          <el-card :body-style="{ padding: '0px' }" shadow="hover" class="guide-card">
            <div class="guide-img">
              <img style="width: 200px; height: 200px;" :src="item.photo || defaultImage" alt="解说员照片">
              <div class="guide-status" :class="getStatusClass(item.status)">
                {{ getStatusText(item.status) }}
              </div>
            </div>
            <div class="guide-info">
              <h3 class="guide-name">{{ item.name }}</h3>
              <p class="guide-language">解说语言：{{ item.language }}</p>
              <div class="guide-intro">{{ item.introduction }}</div>
              <div class="guide-footer">
                <el-button type="primary" size="small" @click="viewDetail(item.id)">查看详情</el-button>
                <el-button 
                  type="success" 
                  size="small" 
                  @click="makeReservation(item)" 
                  :disabled="item.status !== 'AVAILABLE'"
                >预约解说</el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 空数据提示 -->
      <el-empty v-if="guideList.length === 0 && !loading" description="暂无解说员信息"></el-empty>
      
      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[8, 16, 24, 32]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      >
      </el-pagination>
    </el-card>
    
    <!-- 预约对话框 -->
    <el-dialog title="解说预约" :visible.sync="dialogVisible" width="500px">
      <el-form :model="reservationForm" :rules="reservationRules" ref="reservationFormRef" label-width="100px">
        <el-form-item label="解说员">
          <el-input v-model="currentGuide.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="解说语言">
          <el-input v-model="currentGuide.language" disabled></el-input>
        </el-form-item>
        <el-form-item label="展览" prop="exhibitionId">
          <el-select v-model="reservationForm.exhibitionId" placeholder="请选择展览" style="width: 100%">
            <el-option
              v-for="item in exhibitionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约日期" prop="reservationDate">
          <el-date-picker
            v-model="reservationForm.reservationDate"
            type="date"
            placeholder="选择预约日期"
            :picker-options="datePickerOptions"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间段" prop="timeSlot">
          <el-select v-model="reservationForm.timeSlot" placeholder="请选择预约时间段" style="width: 100%">
            <el-option
              v-for="item in timeSlots"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约人数" prop="visitorCount">
          <el-input-number v-model="reservationForm.visitorCount" :min="1" :max="10" style="width: 100%"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReservation" :loading="submitLoading">提交预约</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import { mapGetters } from 'vuex'

export default {
  name: 'GuideList',
  data() {
    return {
      // 解说员列表数据
      guideList: [],
      // 默认解说员照片
      defaultImage: 'https://via.placeholder.com/300x300?text=解说员',
      // 加载状态
      loading: false,
      // 分页参数
      currentPage: 1,
      pageSize: 8,
      total: 0,
      // 搜索关键词
      searchQuery: '',
      // 预约对话框
      dialogVisible: false,
      // 当前选中的解说员
      currentGuide: {},
      // 预约表单
      reservationForm: {
        exhibitionId: '',
        reservationDate: '',
        timeSlot: '',
        visitorCount: 1
      },
      // 预约表单验证规则
      reservationRules: {
        exhibitionId: [
          { required: true, message: '请选择展览', trigger: 'change' }
        ],
        reservationDate: [
          { required: true, message: '请选择预约日期', trigger: 'change' }
        ],
        timeSlot: [
          { required: true, message: '请选择预约时间段', trigger: 'change' }
        ],
        visitorCount: [
          { required: true, message: '请输入预约人数', trigger: 'blur' }
        ]
      },
      // 日期选择器配置
      datePickerOptions: {
        disabledDate(time) {
          // 禁用今天之前的日期
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      // 时间段选项
      timeSlots: [
        { value: '09:00-11:00', label: '上午 09:00-11:00' },
        { value: '13:00-15:00', label: '下午 13:00-15:00' },
        { value: '15:00-17:00', label: '下午 15:00-17:00' }
      ],
      // 展览选项
      exhibitionOptions: [],
      // 提交预约加载状态
      submitLoading: false
    }
  },
  computed: {
    ...mapGetters(['exhibitions'])
  },
  created() {
    // 获取解说员列表
    this.getGuideList()
    // 获取展览列表
    this.getExhibitionOptions()
  },
  methods: {
    // 获取解说员列表
    async getGuideList() {
      this.loading = true
      try {
        const { data: res } = await this.$http.get('/guide/list', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            name: this.searchQuery
          }
        })
        if (res.code === 200) {
          this.guideList = res.data.records || []
          this.total = res.data.total || 0
        } else {
          this.$message.error(res.message || '获取解说员列表失败')
        }
      } catch (error) {
        console.error('获取解说员列表失败', error)
        this.$message.error('获取解说员列表失败，请稍后重试')
        // 使用模拟数据
        this.guideList = this.getMockData()
        this.total = this.guideList.length
      } finally {
        this.loading = false
      }
    },
    // 获取展览选项
    async getExhibitionOptions() {
      try {
        // 如果store中已有展览数据，直接使用
        if (this.exhibitions.length > 0) {
          this.formatExhibitionOptions(this.exhibitions)
        } else {
          // 否则从服务器获取
          await this.$store.dispatch('getExhibitions')
          this.formatExhibitionOptions(this.exhibitions)
        }
      } catch (error) {
        console.error('获取展览选项失败', error)
        // 使用模拟数据
        this.exhibitionOptions = [
          { value: '1', label: '古代陶瓷艺术展' },
          { value: '2', label: '近代绘画作品展' },
          { value: '3', label: '民间工艺品展览' }
        ]
      }
    },
    // 格式化展览选项
    formatExhibitionOptions(exhibitions) {
      // 只选择进行中的展览
      this.exhibitionOptions = exhibitions
        .filter(item => item.status === 'IN_PROGRESS')
        .map(item => ({
          value: item.id,
          label: item.name
        }))
    },
    // 搜索解说员
    searchGuides() {
      this.currentPage = 1
      this.getGuideList()
    },
    // 处理页码变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage
      this.getGuideList()
    },
    // 处理每页条数变化
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.currentPage = 1
      this.getGuideList()
    },
    // 查看解说员详情
    viewDetail(id) {
      // 可以实现详情页，或者使用对话框展示详情
      const guide = this.guideList.find(item => item.id === id)
      if (guide) {
        this.$alert(guide.introduction, guide.name, {
          confirmButtonText: '确定',
          callback: () => {}
        })
      }
    },
    // 获取解说员状态文本
    getStatusText(status) {
      const statusMap = {
        'AVAILABLE': '可预约',
        'UNAVAILABLE': '不可预约'
      }
      return statusMap[status] || '未知'
    },
    // 获取解说员状态样式类
    getStatusClass(status) {
      return {
        'status-available': status === 'AVAILABLE',
        'status-unavailable': status === 'UNAVAILABLE'
      }
    },
    // 打开预约对话框
    makeReservation(guide) {
      if (guide.status !== 'AVAILABLE') {
        return this.$message.warning('该解说员当前不可预约')
      }
      this.currentGuide = guide
      this.dialogVisible = true
      // 重置表单
      this.reservationForm = {
        exhibitionId: '',
        reservationDate: '',
        timeSlot: '',
        visitorCount: 1
      }
      // 如果表单引用存在，重置验证
      if (this.$refs.reservationFormRef) {
        this.$refs.reservationFormRef.resetFields()
      }
    },
    // 提交预约
    submitReservation() {
      this.$refs.reservationFormRef.validate(async valid => {
        if (!valid) return
        this.submitLoading = true
        try {
          // 构建预约数据
          const reservationData = {
            userId: this.$store.state.userInfo.id,
            guideId: this.currentGuide.id,
            exhibitionId: this.reservationForm.exhibitionId,
            reservationDate: moment(this.reservationForm.reservationDate).format('YYYY-MM-DD'),
            timeSlot: this.reservationForm.timeSlot,
            visitorCount: this.reservationForm.visitorCount
          }
          // 发送预约请求
          const { data: res } = await this.$http.post('/guide-reservation', reservationData)
          if (res.code === 200) {
            this.$message.success('预约成功，请在"我的预约"中查看预约详情')
            this.dialogVisible = false
          } else {
            this.$message.error(res.message || '预约失败')
          }
        } catch (error) {
          console.error('预约失败', error)
          this.$message.error('预约失败，请稍后重试')
        } finally {
          this.submitLoading = false
        }
      })
    },
    // 获取模拟数据
    getMockData() {
      return [
        {
          id: '1',
          name: '张明',
          photo: '',
          language: '中文、英文',
          introduction: '从事文物解说工作10年，擅长陶瓷艺术和古代绘画解说，曾获得全国优秀解说员称号。',
          status: 'AVAILABLE'
        },
        {
          id: '2',
          name: '李华',
          photo: '',
          language: '中文、日文',
          introduction: '毕业于中国艺术研究院，专注于民间工艺品和传统文化研究，具有丰富的解说经验。',
          status: 'AVAILABLE'
        },
        {
          id: '3',
          name: '王芳',
          photo: '',
          language: '中文、法文',
          introduction: '文物保护专业出身，对古代文物有深入研究，善于用生动的语言讲述文物背后的历史故事。',
          status: 'UNAVAILABLE'
        },
        {
          id: '4',
          name: '赵伟',
          photo: '',
          language: '中文、德文',
          introduction: '历史学博士，对中国古代历史和文化有深厚的学术背景，解说风格严谨而富有趣味性。',
          status: 'AVAILABLE'
        }
      ]
    }
  }
}
</script>

<style lang="scss" scoped>
.guide-list-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .search-input {
      width: 250px;
    }
  }
  
  .guide-item {
    margin-bottom: 20px;
    
    .guide-card {
      height: 100%;
      
      .guide-img {
        position: relative;
        height: 200px;
        overflow: hidden;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        
        .guide-status {
          position: absolute;
          top: 10px;
          right: 10px;
          padding: 4px 8px;
          color: #fff;
          font-size: 12px;
          border-radius: 4px;
          
          &.status-available {
            background-color: #67c23a;
          }
          
          &.status-unavailable {
            background-color: #f56c6c;
          }
        }
      }
      
      .guide-info {
        padding: 14px;
        
        .guide-name {
          margin: 0 0 10px;
          font-size: 16px;
          font-weight: bold;
        }
        
        .guide-language {
          margin: 5px 0;
          font-size: 14px;
          color: #606266;
        }
        
        .guide-intro {
          margin: 10px 0;
          font-size: 13px;
          color: #606266;
          line-height: 1.5;
          height: 60px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }
        
        .guide-footer {
          margin-top: 15px;
          display: flex;
          justify-content: space-between;
        }
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    text-align: center;
  }
}